<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;

use common\models\WeChat;
use common\tools\WeChatTool;
use common\tools\HttpTool;
/**
 * Description of WeiChatController
 *
 * @author weiwangw
 */
class WechatController extends Controller{
    
    public $enableCsrfValidation = false;//关闭csrf
    
    public function actionIndex($code=1)
    {
        $get = Yii::$app->request->get();
        if (isset($get['echostr'])) {
            if($this->checkSignature()){
                echo $get['echostr'];
                exit;
            }
        }else{
//            print_r(WeChat::getinstance()->responseMsg());die;
            return WeChat::getinstance()->responseMsg();
        }
    }
    
    private function checkSignature(){
        $get       = Yii::$app->request->get();
        $signature = $get["signature"];
        $timestamp = $get["timestamp"];
        $nonce     = $get["nonce"];	

        $token     = \Yii::$app->params["weixinConf"]['token'];
        $tmpArr    = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr    = implode( $tmpArr );
        $tmpStr    = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * 菜单
     */
    public function actionMenu(){
        $menu    = \Yii::$app->params["menu"];
        $token   = WeChatTool::getToken();
        $url     = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$token}";      
        $tmpInfo = HttpTool::http_post($url, $menu);
        $result  = json_decode($tmpInfo,true);

        if($result['errcode']){
            echo $tmpInfo;
        }else{
            echo "生成成功,24小时后生效(有时候几分钟后也生效)";
        }
    }
}
